/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim </a>, 2004
 */
package hk.com.carfield.util;

import hk.com.carfield.core.MailManager;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang.exception.ExceptionUtils;

public final class LogUtil {
	static Logger logger = Logger.getLogger("log");
	public static void init(final File root) throws IOException {
        final int limit = 32*1024*1024;
        final FileHandler fh = new FileHandler(new File(root, "log").getAbsolutePath(), limit, 1);
        logger = Logger.getLogger("log");
        logger.addHandler(fh);
	}

	public static void log(final Object[] o) {
		logger.log(Level.INFO, "size is "+o.length);
		for (int i = 0; i < o.length; i++) {
			logger.log(Level.INFO, i+" is "+o[i].toString());
		}
	}

	public static void log(final String s) {
		logger.log(Level.INFO, s);
	}

	public static String error(final String errMsg, final MailManager mailMan) {
		final String errorId = String.valueOf(TimeUtil.currentTime());
		logger.log(Level.SEVERE , "\n\n\n=====ErrorId=====\n\n"+errorId+errMsg);
		if(mailMan != null)
			mailMan.send("website error", errMsg);
		return errorId;
	}

	public static String error(final Throwable t, final MailManager mailMan, final File file, final Request request) {
		final String fileMsg = file == null ? "" : "\n=====File=====\n"+file.getAbsolutePath();
		final String requestMsg = request == null ? "":"\n=====request=====\n"+request == null ? "":request.toString();
		return error(fileMsg+requestMsg+
				"\n=====StackTrace=====\n"+ExceptionUtils.getFullStackTrace(t), mailMan);
	}

	public static String error(final Throwable t, final MailManager mailMan) {
		return error(t, mailMan, null, null);
	}

	public static String error(final Throwable t, final MailManager mailMan, final File f) {
		return error(t, mailMan, f, null);
	}
}